package com.jzsm.modules.sender.senderService.impl.dingtalk.utils;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.jzsm.modules.sender.bo.accountConfig.DingtalkAppAccountConfigBo;
import com.jzsm.modules.sender.enums.DomainNameEnum;
import com.jzsm.common.utils.AssertUtils;
import com.taobao.api.ApiException;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;

import java.util.Map;

@FieldDefaults(level = AccessLevel.PRIVATE)
public class DingtalkUtils {
    static final String PREFIX_URL = DomainNameEnum.Dingtalk.getUrl();
    static final String ACCESS_TOKEN_FIELD = "access_token";


    /**
     * 获取  access_token
     *
     * @param configBo
     * @return
     */
    public static String getAccessToken(DingtalkAppAccountConfigBo configBo) {
        DingTalkClient client = new DefaultDingTalkClient(PREFIX_URL + "/gettoken");
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(configBo.getAppKey());
        req.setAppsecret(configBo.getAppSecret());
        req.setHttpMethod("GET");
        OapiGettokenResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            AssertUtils.throwError(e.getMessage());
        }
        AssertUtils.isTrue("获取 access_token 失败：" + rsp.getErrmsg(), rsp.isSuccess());
        Map map = JSON.parseObject(rsp.getBody(), Map.class);
        return (String) map.get(ACCESS_TOKEN_FIELD);
    }
}
